from flask import Flask, jsonify, request, url_for, Response
import pymysql
import sqlite3

app = Flask(__name__, static_folder='spa', static_url_path='/spa')


@app.delete('/book')
def book():
    id2 = request.args.get('id')
    return jsonify({'msg': f'你正在删除ID为{id2}的书籍', 'data': None, 'code': 200})


@app.route('/store')
def all_goods():
    conn = pymysql.connect(host='localhost', user='python_class', password='python_class', database='python_class')
    cursor = conn.cursor()
    sql = 'SELECT * FROM store'
    cursor.execute(sql)
    result = cursor.fetchall()
    cursor.close()
    conn.close()

    return jsonify({'msg': 'success', 'data': result, 'code': 200})


@app.route('/store/add')
def add_goods():
    title = request.args.get('title')
    price = request.args.get('price')
    conn = pymysql.connect(host='localhost', user='python_class', password='python_class', database='python_class')
    cursor = conn.cursor()
    effected = cursor.execute(f"INSERT INTO store(`title`, `price`) VALUES ('{title}',{price})")
    conn.commit()

    cursor.close()
    conn.close()

    return jsonify({'msg': 'add success!', 'data': effected, 'code': 200})


@app.delete('/store')
def delete_goods():
    id = int(request.args.get('id'))
    conn = pymysql.connect(host='localhost', user='python_class', password='python_class', database='python_class')
    cursor = conn.cursor()
    effected = cursor.execute(f"DELETE FROM `store` WHERE id = %s", id)

    conn.commit()
    cursor.close()
    conn.close()

    return jsonify({'msg': 'delete success!', 'data': effected, 'code': 200})


@app.route('/register')
def register():
    info = request.args

    return jsonify({"msg": info})


@app.route('/heartbeat')
def heartbeat():
    return jsonify({'status': 'healthy'})


@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    if path is None or len(path) == 0 or path == '/':
        path = 'index.html'
    file = open('spa/' + path, 'rb')

    if '.js' in path:
        return Response(file, mimetype='application/javascript')
    if '.css' in path:
        return Response(file, mimetype='text/css')
    if '.svg' in path:
        return Response(file, mimetype='image/svg+xml')
    if '.jpg' in path or '.jpeg' in path:
        return Response(file, mimetype='image/jpg')
    if '.png' in path:
        return Response(file, mimetype='image/png')

    return app.send_static_file('index.html')


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=3006)
